import { Router } from "vue-router"
import { userStore,routeStore,menuStore } from "@/store/index";
import { storeToRefs } from 'pinia'
const whiteList = ['/login']
export function createRouterGuards(router: Router){
	router.beforeEach(async (to, from, next) => {
		const store = userStore()
		const {token} = storeToRefs(store)
		const route_store = routeStore()
		const menu_store = menuStore()
		const {frontRoutes,backRoutes} = storeToRefs(route_store)
		const {menuType} = storeToRefs(menu_store)
		const {fullPath} = to
		const isExist = router.getRoutes().filter(item=>item.path === fullPath).length > 0
		if (token.value) {
			const {user:{roleIds}} = store
			// 存在临时路由先删除路由
			// token有值
			if(menuType.value === 3){
				if(backRoutes.value.length === 0){
					await route_store.getRoutes(menuType.value,roleIds)
				}
				if(isExist){
					next()
				}else{
					return next({ ...to, replace: true })
				}
			}
			if(menuType.value === 1){
				if(frontRoutes.value.length === 0){
					await route_store.getRoutes(menuType.value,roleIds)
				}
				if(isExist){
					next()
				}else{
					return next({ ...to, replace: true })
				}
			}
		}else{
			if (whiteList.indexOf(to.path) !== -1) {
			    next()
			} else {
			    next({path: `/login?redirect=${to.path}`})
			}
		}
	})
	router.afterEach(()=>{
		console.log(router.getRoutes())
	})
}